
import React, { useState, useEffect, useRef } from 'react'
import { Layout, Row, Col, Button, Modal, message, PageHeader, Form, Spin, Input } from 'antd';
import { LeftOutlined } from '@ant-design/icons';
import { setStore, getStore } from '@/utils/commons'
import QRCode from "qrcode.react";
import copy from "copy-to-clipboard";
import HeaderBox from '@/components/header'
import FooterBox from '@/components/footer'
import UserMenu from '@/components/userMenu'
import VerifyBox from '@/components/verifyBox'
import API from '@/api/api'
import Funs from '@/utils/Funs'
import coinBtc from '../../assets/img/icon/btc.png'
import coinUsdt from '../../assets/img/icon/usdt.png'
import coinEth from '../../assets/img/icon/eth.png'
import coinIpfs from '../../assets/img/icon/ipfs.png'
import './index.scss';
const { Content } = Layout;

function Withdraw(props) {
    const [load, setLoad] = useState(true)
    const [inload, setInLoad] = useState(false)
    const [coinName, setCoinName] = useState()
    const [coinId, setCoinId] = useState()
    const [userVerify, setUserVerify] = useState()
    const [withdrawInfo, setWithdrawInfo] = useState()
    const [balance, setBalance] = useState(0)
    const [realNum, setRealNum] = useState(0)
    const [withdrawType, setWithdrawType] = useState('phone')
    const [timer, setTimer] = useState(0)
    const coinImg = { 'BTC': coinBtc, 'USDT': coinUsdt, 'ETH': coinEth, 'FIL': coinIpfs }
    const [form] = Form.useForm();
    const verifyRef = useRef();

    useEffect(() => {
        getUserVerify()
        getWithdrawInfo()
    }, [])

    const getUserVerify = () => {
        if (getStore('userVerify')) {
            let jsonData = JSON.parse(getStore('userVerify'))
            setUserVerify(jsonData)
        } else {
            props.history.push('/')
        }
    }

    const getWithdrawInfo = async () => {
        let name = props.match.params.name
        let opts = { coinName: name }
        let res = await API.withdrawInfo(opts)
        if (res && res.data) {
            setCoinName(name)
            setBalance(res.data.balance)
            setCoinId(res.data.coin[0].id)
            setWithdrawInfo(res.data.coin[0].withdraw)
            setLoad(false)
        } else {
            setLoad(false)
        }
    }

    const cancelVerifyModal = () => {
        verifyRef.current.cancelModal()
    }

    const openVerifyModal = type => {
        setWithdrawType(type)
        verifyRef.current.openModal()
    }

    const sendCaptcha = async (captcha, key) => {
        let opts = { action: 'withdraw', type: withdrawType, captcha: captcha, captchaKey: key };
        const fileds = JSON.parse(getStore('userInfo'))
        if (withdrawType === 'phone') {
            opts.phone = fileds.phone
            opts.phoneArea = fileds.phone_area
        } else {
            opts.email = fileds.email
        }
        if (!captcha) {
            message.warning('请输入图形验证码')
            return false
        }
        console.log(opts)
        if (timer === 0) {
            let sendCaptchaRes = await API.sendVerify(opts);
            if (sendCaptchaRes) {
                setTimer(60)
                message.success("已成功发送验证码");
                cancelVerifyModal()
            }
        } else {
            message.warning("验证码发送间隔太短，请稍后再试")
        }
    }

    const onFinish = async (values) => {
        console.log(values)
        let opts = { ...values, coinId: coinId }
        setInLoad(true)
        let res = await API.withdraw(opts)
        if (res) {
            setInLoad(false)
            message.success('转账申请成功')
            props.history.push('/wallet')
        } else {
            setInLoad(false)
        }
    }

    const onChange = async (e) => {
        let num = e.target.value
        if (withdrawInfo.fee_rate > 0) {
            num = num - num * withdrawInfo.fee_rate
        } else {
            num = num - withdrawInfo.fee
        }
        setRealNum(num > 0 ? num : 0)
    }

    const buttonPhoneAfter = (
        <a className="captcha-btn" onClick={() => openVerifyModal('phone')}> {timer === 0 ? '发送验证码' : timer + '秒'}</a>
    )

    const buttonEmailAfter = (
        <a className="captcha-btn" onClick={() => openVerifyModal('email')}> {timer === 0 ? '发送验证码' : timer + '秒'}</a>
    )

    return (
        <Layout className="layout">
            <HeaderBox />
            <Content>
                {inload ? <div className="load-mark"><Spin /></div> : null}
                <Row className="withdraw main" justify="space-between">
                    <Col lg={4} md={20}>
                        <UserMenu current="3" />
                    </Col>
                    <Col className="wallet-main" lg={19} md={20}>
                        <Row className="page-title" align="middle" onClick={() => props.history.push('/wallet')}>
                            <p><LeftOutlined /> 上一页</p>
                            <p className="title">提现</p>
                        </Row>
                        {
                            load ? < div className="load-box"><Spin /></div> :
                                <Form className="withdraw-form" form={form} onFinish={onFinish} >
                                    <p>提现地址</p>
                                    <Form.Item name="toAddress" rules={[
                                        { required: true, message: '请输入提现地址' }
                                    ]}>
                                        <Input className="withdraw-input" placeholder="请输入提现地址" />
                                    </Form.Item>
                                    <p>提现数量</p>
                                    <Form.Item name="total" rules={[
                                        { required: true, message: '请输入提现数量' },

                                    ]}>
                                        <Input className="withdraw-input" placeholder="请输入提现数量" min="0" maxLength="16" suffix={<a>全部提现</a>} onChange={onChange} />
                                    </Form.Item>
                                    <Row>
                                        {userVerify && userVerify.phone ?
                                            <Col span={12}>
                                                <p>手机验证码</p>
                                                <Form.Item name="phoneCaptcha" rules={[
                                                    { required: true, message: '请输入手机验证码' }
                                                ]}>
                                                    <Input className="withdraw-input-half" placeholder="请输入手机验证码" suffix={buttonPhoneAfter} />
                                                </Form.Item></Col> : null}
                                        {userVerify && userVerify.email ?
                                            <Col span={12}>
                                                <p>邮箱验证码</p>
                                                <Form.Item name="emailCaptcha" rules={[
                                                    { required: true, message: '请输入邮箱验证码' }
                                                ]}>

                                                    <Input className="withdraw-input-half" placeholder="请输入邮箱验证码" suffix={buttonEmailAfter} />
                                                </Form.Item></Col> : null}
                                        {userVerify && userVerify.googleAuth ?
                                            <Col span={12}>
                                                <p>谷歌验证码</p>
                                                <Form.Item name="googleOnceCode" rules={[
                                                    { required: true, message: '请输入谷歌验证码' }
                                                ]}>

                                                    <Input className="withdraw-input-half" placeholder="请输入谷歌验证码" />
                                                </Form.Item></Col> : null}
                                        {userVerify && userVerify.paymentPassword ?
                                            <Col span={12}>
                                                <p>交易密码</p>
                                                <Form.Item name="paymentPassword" rules={[
                                                    { required: true, message: '请输入交易密码' }
                                                ]}>

                                                    <Input.Password className="withdraw-input-half" placeholder="请输入交易密码" />
                                                </Form.Item></Col> : null}
                                    </Row>
                                    <Row>
                                        <Col span={12}>
                                            <p>该币种提现手续费为</p>
                                            <Form.Item>
                                                <Input className="withdraw-input-half" suffix={withdrawInfo.fee_rate ? '%' : coinName}
                                                    value={withdrawInfo.fee_rate ? Funs.toNum(withdrawInfo.fee_rate * 100) : Funs.toNum(withdrawInfo.fee)} disabled />
                                            </Form.Item></Col>
                                        <Col span={12}>
                                            <p>实际到账数量</p>
                                            <Form.Item>
                                                <Input className="withdraw-input-half" suffix={coinName} value={realNum} disabled />
                                            </Form.Item></Col>
                                    </Row>
                                    <Form.Item >
                                        <Button type="primary" htmlType="submit" className="withdraw-submit">
                                            提现
                                        </Button>
                                    </Form.Item>
                                </Form>
                        }
                        {load ? null :
                            <Row className="withdraw-tip">
                                <h3>温馨提示</h3>
                                {withdrawInfo.max > 0 ?
                                    <p>*提币范围为 {withdrawInfo && Funs.toNum(withdrawInfo.min)}~{withdrawInfo && Funs.toNum(withdrawInfo.max)} {coinName}</p> : null
                                }
                                <p>*为保障资金安全，当您账户安全策略变更、密码修改、我们会对提币进行人工审核，请耐心等待工作人员电话或邮件联系</p>
                                <p>*请务必确认电脑及浏览器安全，防止信息被篡改或泄露</p>
                                <p>*您可以在提现记录页面跟踪状态</p>
                                <p>*该币种提币手续费具体情况，是由对应公链的手续费决定</p>
                            </Row>
                        }
                    </Col>
                </Row>
            </Content>
            <VerifyBox ref={verifyRef} send={sendCaptcha} />
            <FooterBox />
        </Layout>
    )
}

export default Withdraw